/**
 * 统一的请求对象
 */

import {
	getState,
	setState
} from "@/store";
import {
	weBtoa,
	weAtob
} from './weapp-jwt-decode.js'

const showMessage = title => {
	uni.showToast({
		icon: "none",
		position: "bottom",
		title,
	});
}

/**
 * 数据加密解密类
 */



class unscrambler {
	constructor(setDecode, getDecode) {
		Object.assign(this, {
			setDecode,
			getDecode
		});
	}
}

const setDecode = setObj => {
	if (Object.keys(setObj).length > 0) setObj = JSON.stringify(setObj);
	let set = encodeURIComponent(setObj),
		result = btoa(set);
	// result = weBtoa(set)
	return result;
}


const getDecode = getData => {
	let jieMi = atob(getData),
		// let jieMi = weAtob(getData),
		jieM = decodeURIComponent(jieMi);
	try {
		return JSON.parse(jieM)
	} catch (e) {
		return false
	}
}
/**
 * 类 数据转base64类
 * 小程序不支持  btoa  atob 函数 需要引用 以下库
 * https://github.com/equicy/weapp-jwt-decode
 */
let decode = new unscrambler(setDecode, getDecode);

export default class RequestHttp {

	static req(Interface, data, method = "POST", dataType = "json") {
		let sendData = data && decode.setDecode(data);
		let url = `${getState("api", "baseUrl")}${Interface}`;
		let Authorization;
		uni.getStorage({
			key: 'userInfo',
			success: (res) => {
				Authorization = res.data.token
			}
		});

		return new Promise((resolve, reject) => {
			uni.request({
				url,
				data: sendData,
				header: {
					SelfSummerHeader: "hello", //自定义请求头信息
					"content-type": "text/xml",
					// "content-type": 'application/xml',
					Authorization
				},
				method,
				dataType,
				fail() {
					showMessage("网络请求失败");
				},
				success(response) {
					!response.data && showMessage("接口报错，报文无data数据");

					if (response && (response.statusCode === 200 || response.statusCode === 304 ||
							response.statusCode === 400)) {
								
								console.log(typeof response.data)


						const receiveData = typeof response.data === 'string' ? decode.getDecode(response.data) : response.data;
						switch (receiveData.StatusCode) {
							// 当请求返回是的状态码正确是才返回数据
							case 200:
								let data = receiveData.data;

								if (Array.isArray(data)) {
									data.forEach((item) => {
										item.img =
											`${this.baseHttpUrl}${item.img || "pudate/005100-1592412660f973.jpg"}`;
									});
								}

								// if (typeof data === "object") {
								// 	for (let k in data) {
								// 		if (k === "img") {
								// 			data[k] =
								// 				`${this.baseHttpUrl}pudate/4b2ae6458a8b43e98524a13cdfd3d609_th.jpg`
								// 		}
								// 	}
								// }

								resolve(data);
								break;
							case 100:
								showMessage("账户已被注册");
								break;
							case 240:
								showMessage("用户不存在");
								break;
							case 250:
								showMessage("验证码错误");
								break;
							case 260:
								showMessage("密码错误");
								break;
							case 444:
								showMessage("操作失败");
								break;
							case 100:
								showMessage("selfsummerheader错误");
								break;
							case 1000:
								showMessage("登录超时");
								uni.navigateTo({
									url: `/`,
								});
								break;
							default:
								showMessage(receiveData.msg);
								// showMessage('请求失败');
								console.log(response);
								reject(response);
						}
					} else {
						showMessage("网络异常");
					}
				},
			});
		});
	}

	/**
	 * uniapp 多图上传方法
	 * Interface,地址
	 * filePath,文件数组,
	 * formData, 额外的参数
	 * name NodeJS 服务获取的KEY
	 */
	static reqFile(Interface, files, formData, name = "file") {
		let url = `${getState("api", "baseUrl")}${Interface}`;
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url,
				files,
				name,
				formData,
				success: (uploadFileRes) => {
					let {
						statusCode,
						errMsg,
						data
					} = uploadFileRes;

					let dataType = '';

					try {
						dataType = typeof JSON.parse(data)
					} catch (e) {
						dataType = 'string'
					}

					if (statusCode === 200) {
						console.log(dataType === 'object' ,data)
						const receiveData = dataType === 'object' ? JSON.parse(data) : decode.getDecode(data);
						console.log(statusCode, receiveData)
						let setverData = receiveData
						setverData.StatusCode === 200 ?
							resolve(setverData.data) :
							showMessage(setverData.msg);
					} else {
						showMessage(errMsg);
					}
				},
				file: (err) => {
					reject(err);
				},
			});
			uploadTask.onProgressUpdate((res) => {
				// console.log(res);
				// console.log("上传进度" + res.progress);
				// console.log("已经上传的数据长度" + res.totalBytesSent);
				// console.log("预期需要上传的数据总长度" + res.totalBytesExpectedToSend);
			});
		});
	}
	static getimg(url, data, cb) {
		url = `${getState("api", "baseUrl")}${url}`;
		uni.request({
			url, //仅为示例，并非真实接口地址。
			data,
			method: "POST",
			header: {
				SelfSummerHeader: "hello", //自定义请求头信息
				"content-type": "application/json",
			},
			success: (response) => {
				if (!response.data) {
					showMessage("接口报错，报文无data数据");
				}
				return response.data.data;
				// console.log(response.data.data);
			},
		});
	}

	static MusicRequest(Interface, data, method = "GET") {
		let url = `${getState("api", "baseMusicUrl")}${Interface}`;
		return new Promise((resolve, reject) => {
			uni.request({
				url,
				data,
				header: {
					// SelfSummerHeader: "hello", //自定义请求头信息
					"content-type": "application/json; charset=utf-8"
				},
				method,
				fail() {
					showMessage("网络请求失败");
				},
				success(response) {
					!response.data && showMessage("接口报错，报文无data数据");
					if (response && (response.statusCode === 200 || response.statusCode === 304 ||
							response.statusCode === 400)) {
						switch (response.data.code) {
							// 当请求返回是的状态码正确是才返回数据
							case 200:
								resolve(response.data);
								break;
							case 1000:
								showMessage("登录超时");
								uni.navigateTo({
									url: `/`,
								});
								break;
							default:
								showMessage(response.msg);
								reject(response);
						}
					} else {
						showMessage("网络异常");
					}
				},
			});
		});
	}
};
